<?php


namespace app\controller\admin\partner;


use app\common\exception\ApiException;
use app\controller\admin\BaseAdminController;
use app\model\goods\OrderModel;
use app\model\partner\EscortMenuOrderLogModel;
use app\model\partner\EscortMenuOrderModel;
use app\model\partner\EscortMenuReserveOrderModel;
use app\model\partner\UserPartnerModel;
use app\model\user\UserModel;
use app\service\config\ConfigService;
use app\service\config\DutyService;
use app\service\order\PartnerOrderService;
use app\service\utils\GenerateUserNickService;
use think\facade\Db;

class OrderController extends BaseAdminController
{

    function setModel()
    {
        return new EscortMenuOrderModel();
    }

    function setWithModel()
    {
        return ['user', 'source', 'userCity'];
    }

    function setSearch()
    {
        $where = [];
        $where[] = ['pay_status', 'in', [2, 3]];
//        $where[] = ['is_trial', '=', 0];
        return [
            '=' => ['user.mobile' => 'mobile', 'order_type', 'user_city_id'],
            'betweenTimestamp' => ['create_time'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        // TODO: Implement setSort() method.
    }

    /**
     * 统计
     * @return \think\response\Json
     */
    public function getTotalList()
    {
        try {
            $where = [];
            $where[] = ['pay_status', 'in', [2, 3]];
            $where[] = ['order_type', '=', 1];
//            $where[] = ['is_trial', '=', 0];
            $mobile = $this->request->param('mobile', '', 'trim');
            if ($mobile) {
                $userId = UserModel::where('mobile', $mobile)->value('id');
                $where[] = ['user_id', '=', $userId];
            }
            $cityId = $this->request->param('city_id', '', 'trim');
            if ($cityId) {
                $where[] = ['city_id', 'like', '%' . $cityId . '%'];
            }
            $createTime = $this->request->param('create_time', '', 'trim');
            if ($createTime) {
                $where[] = ['create_time', '>=', strtotime($createTime[0])];
                $where[] = ['create_time', '<', strtotime($createTime[1]) + 86400];
            }
            $list = $this->setModel()->where($where)->select()->toArray();
            $total = count($list);
            $totalAmount = array_sum(array_column($list, 'amount'));
            $totalPayAmount = array_sum(array_column($list, 'pay_amount'));
            $totalUsed = array_sum(array_column($list, 'residue_duration'));
            return $this->success([
                'total' => $total,
                'amount' => $totalAmount,
                'pay_amount' => $totalPayAmount,
                'duration' => $totalUsed
            ]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 修改时长
     * @return \think\response\Json
     */
    public function modifyDuration()
    {
        try {
            $id = $this->request->param('id', '');
            $duration = $this->request->param('duration', '');
            $remark = $this->request->param('order_remark', '', 'trim');
            if ($remark == '') {
                throw new ApiException('请填写备注');
            }
            $escortMenuOrderModel = EscortMenuOrderModel::find($id);
            if (!$escortMenuOrderModel) {
                throw new ApiException('订单不存在');
            }
            $escortMenuOrderModel->residue_duration = $duration;
            $escortMenuOrderModel->used_duration = $escortMenuOrderModel['total'] - $duration;
            $escortMenuOrderModel->valid_time = $escortMenuOrderModel['valid_time'] + 90 * 86400;
            $escortMenuOrderModel->save();

            $escortMenuOrderLogModel = new EscortMenuOrderLogModel();
            $escortMenuOrderLogModel->order_sn = $escortMenuOrderModel->order_sn;
            $escortMenuOrderLogModel->total = $escortMenuOrderModel->total;
            $escortMenuOrderLogModel->used_duration = $escortMenuOrderModel->used_duration;
            $escortMenuOrderLogModel->residue_duration = $duration;
            $escortMenuOrderLogModel->remark = $remark;
            $escortMenuOrderLogModel->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 添加订单
     * @return \think\response\Json
     */
    public function save()
    {
        try {
            $data = $this->request->only(['source_id', 'city_id', 'amount', 'total', 'mobile', 'order_remark',
                'is_trial', 'menu_name'], 'param', 'trim');

            $userId = UserModel::where('mobile', $data['mobile'])->value('id', 0);
            if (!$userId) {
                $userModel = new UserModel();
                $userModel->mobile = $data['mobile'];
                $userModel->username = GenerateUserNickService::generateUserNick();
                $userModel->save();
                $userId = $userModel->id;
            }
            if (isset($data['is_trial']) && $data['is_trial'] == 1) {
                $orderInfo = EscortMenuOrderModel::where('user_id', $userId)
                    ->where('is_trial', 1)
                    ->find();
                if ($orderInfo) {
                    throw new ApiException('只能有一次体验课');
                }
            }
            $orderSn = createOrderSn('order', 'order_sn', 'HTC');

            // 生成一个套餐订单
            $escortMenuOrderModel = new EscortMenuOrderModel();
            $escortMenuOrderModel->user_id = $userId;
            $escortMenuOrderModel->order_sn = $orderSn;
            $escortMenuOrderModel->amount = $data['amount'];
            $escortMenuOrderModel->pay_amount = $data['amount'];
            $escortMenuOrderModel->pay_status = 2;
            $escortMenuOrderModel->pay_time = time();
            $escortMenuOrderModel->total = $data['total'];
            $escortMenuOrderModel->min = 2;
            $escortMenuOrderModel->city_id = $data['city_id'];
            $escortMenuOrderModel->source_id = $data['source_id'];
            $escortMenuOrderModel->valid_time = time() + 360 * 86400;
            $escortMenuOrderModel->residue_duration = $data['total'];
            $escortMenuOrderModel->is_trial = $data['is_trial'];
            $escortMenuOrderModel->menu_price = $data['amount'];
            $escortMenuOrderModel->menu_old_price = $data['amount'];
            $escortMenuOrderModel->menu_name = $data['menu_name'];
            $escortMenuOrderModel->menu_image = ConfigService::getConfigValue('goods_img');
            $escortMenuOrderModel->order_remark = $data['order_remark'] ?? '';
            $escortMenuOrderModel->save();

            // 套餐使用日志
            $escortMenuOrderLogModel = new EscortMenuOrderLogModel();
            $escortMenuOrderLogModel->order_sn = $escortMenuOrderModel->order_sn;
            $escortMenuOrderLogModel->total = $escortMenuOrderModel->total;
            $escortMenuOrderLogModel->residue_duration = $escortMenuOrderModel->residue_duration;
            $escortMenuOrderLogModel->coach_id = $userId;
            $escortMenuOrderLogModel->remark = '后台添加套餐订单';
            $escortMenuOrderLogModel->save();

            // 后台添加正式套餐订单
            PartnerOrderService::setPartnerRatio($escortMenuOrderModel['user_id'], $data['is_trial']);

            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}